﻿using B.S.Data.MES.API.Applications.QualityManagement.ExamineTypeModel.Command;
using B.S.Domain.BasicData.QualityManagement;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;

namespace B.S.Data.MES.API.Applications.QualityManagement.ExamineTypeModel.CommandHandler
{
    public class GetExamineTypeCommandHandler : IRequestHandler<GetExamineTypeCommand, APIRequst<APIPageing<List<ExamineType>>>>
    {
        private readonly IBaseRepository<ExamineType> _typeRepository;
        public GetExamineTypeCommandHandler(IBaseRepository<ExamineType> typeRepository)
        {
            
            _typeRepository = typeRepository;
        }
        public Task<APIRequst<APIPageing<List<ExamineType>>>> Handle(GetExamineTypeCommand request, CancellationToken cancellationToken)
        {
            APIRequst<APIPageing<List<ExamineType>>> result = new APIRequst<APIPageing<List<ExamineType>>>();
            result.Code = RequstCode.成功;
            result.Msg = RequstCode.成功.ToString();

            var list=_typeRepository.GetAll().Where(x=>!x.isDel);
            
            if(!string.IsNullOrEmpty(request.ExamineNo))
            {
                list=list.Where(x=>x.ExamineNo==request.ExamineNo);
            }
            if(!string.IsNullOrEmpty(request.ExamineName))
            {
                list = list.Where(x => x.ExamineName.Contains(request.ExamineName));
            }
            int recordcount = list.Count();
            int pagecount = (int)Math.Ceiling(recordcount * 1.0 / request.PageSize);

            list = list.OrderByDescending(x => x.ExamineId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);

            APIPageing<List<ExamineType>> paing = new APIPageing<List<ExamineType>>();
            paing.TotalCount = recordcount;
            paing.Total=pagecount;
            paing.Data = list.ToList();
            result.Data = paing;

            return Task.FromResult(result);

        }
    }
}
